<template>
  <div id="dialogIntegralActionEdit">
    <el-dialog
      title="编辑"
      :visible.sync="dialogData.isShow"
      width="735px"
      top="50px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="demo-ruleForm"
        >
          <el-form-item label="任务名称" prop="">
            <el-input
              v-model="taskName"
              :disabled="true"
              placeholder="请输入任务名称"
            ></el-input>
          </el-form-item>
          <h1 class="form-title">
            积分规则设置<span class="tips-box">
              （规则保存后，将于次日零点生效！） </span
            >：
          </h1>
          <components
            :is="comName"
            ref="ruleSettingCom"
            @setComRuleForm="setComRuleForm"
          ></components>
          <!--新手任务，不显示任务有效期-->
          <el-form-item
            label="任务有效期"
            prop="taskValidity"
            class="taskValidity"
            v-if="category !== 'NEW_TASK'"
          >
            <el-radio-group v-model="ruleForm.taskValidity">
              <el-radio
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
            <el-form-item
              label=""
              prop="createTime"
              v-if="ruleForm.taskValidity === 'false'"
              class="date-line"
            >
              <el-date-picker
                v-model="ruleForm.createTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期时间"
                end-placeholder="结束日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表单部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import firstRegisterModifyModel from '@component/intergralManagement/integralAction/com/firstRegistration' // 首次注册
import bingPhoneModifyModel from '@component/intergralManagement/integralAction/com/bindingMobile' // 绑定手机号码
import perfectInformationModifyModel from '@component/intergralManagement/integralAction/com/personalInfo' // 完善个人信息
import signTaskModifyModel from '@component/intergralManagement/integralAction/com/signIn' // 每日签到
import submitJobModifyModel from '@component/intergralManagement/integralAction/com/submitJob' // 提交作业
import publishWorksModifyModel from '@component/intergralManagement/integralAction/com/pubWorkActive' // 发布作品动态
import commentReplyModifyModel from '@component/intergralManagement/integralAction/com/commentReply' // 评论/回复
import shareTaskModifyModel from '@component/intergralManagement/integralAction/com/share' // 分享
import likeTaskModifyModel from '@component/intergralManagement/integralAction/com/enjoy' // 喜欢
import browsePageModifyModel from '@component/intergralManagement/integralAction/com/browsePage' // 浏览页面
import voteTaskModifyModel from '@component/intergralManagement/integralAction/com/vote' // 投票
import learnCourseModifyModel from '@component/intergralManagement/integralAction/com/listenToClass' // 听课
import {
  sysNormalDisable,
  getVestList,
  getRandomRobotId
} from '@utils/dictionariesFunc'
import { pubVideo, getDetail, editVideo } from '@/api/workManagement/videoBatch'
import { getKeyValue } from '@/api/system/parameter'
import {
  getFormDetail,
  editStrategy
} from '@/api/couponsIntegral/integralAction' //接口
export default {
  msg: '小视频批量维护-编辑弹窗',
  props: ['dialogData'],
  components: {
    firstRegisterModifyModel,
    bingPhoneModifyModel,
    perfectInformationModifyModel,
    signTaskModifyModel,
    submitJobModifyModel,
    publishWorksModifyModel,
    commentReplyModifyModel,
    shareTaskModifyModel,
    likeTaskModifyModel,
    browsePageModifyModel,
    voteTaskModifyModel,
    learnCourseModifyModel
  },
  watch: {
    'ruleForm.createTime': {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 1) {
          this.ruleForm.startDate = newVal[0]
          this.ruleForm.endDate = newVal[1]
        } else {
          this.ruleForm.startDate = ''
          this.ruleForm.endDate = ''
        }
      },
      deep: true
    },
    'ruleForm.taskValidity': {
      handler(newVal, oldVal) {
        if (newVal === 'true') {
          this.ruleForm.createTime = []
        }
      },
      deep: true
    }
  },
  data() {
    return {
      loading: false,
      typeList: [], // 任务有效期
      comName: '',
      category: '', //任务类型
      taskName: '',
      ruleForm: {
        taskValidity: '', // 任务有效期
        createTime: [],
        startDate: '',
        endDate: ''
      },
      comRuleForm: {},
      rules: {
        taskValidity: {
          required: true,
          message: '任务有效期不能为空',
          trigger: 'bluer'
        },
        createTime: {
          type: 'array',
          required: true,
          message: '时间区间不能为空',
          trigger: 'bluer'
        }
      }
    }
  },
  mounted() {
    //通过任务类型，判断展示组件
    this.comName = this.dialogData.params.modelType
    this.category = this.dialogData.params.category
    this.taskName = this.dialogData.params.taskName
    this.getStatusList()
    this.getData()
  },
  methods: {
    /* 获取筛选条件 */
    async getStatusList() {
      // 操作类型
      this.typeList = await sysNormalDisable('strategy_task_validity')
      this.ruleForm.taskValidity = this.typeList[0].dictValue
    },
    /* 获取表单详情 */
    getData() {
      getFormDetail(
        this.dialogData.params.id,
        (response) => {
          let { taskValidity, endTime, startTime } = response
          this.ruleForm.taskValidity = taskValidity.toString()
          if (!taskValidity) {
            //短期
            this.ruleForm.createTime = [startTime, endTime]
          }
          this.$refs.ruleSettingCom.setForm(response)
        },
        (response) => {
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.params = {}
    },
    setComRuleForm(obj) {
      this.comRuleForm = { ...obj }
    },
    checkForm() {
      let _this = this
      return new Promise((resolve, reject) => {
        _this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            resolve(true)
          } else {
            reject(false)
          }
        })
      })
    },
    /* 确认提交 */
    async confirmLabel(formName) {
      let _this = this
      Promise.all([
        _this.$refs.ruleSettingCom.checkForm(),
        _this.checkForm()
      ]).then(([comCheck, formCheck]) => {
        this.loading = true
        let obj = Object.assign({}, this.ruleForm, this.comRuleForm)
        if (this.category === 'NEW_TASK') {
          //新手任务
          delete obj.taskValidity
          delete obj.startDate
          delete obj.endDate
        }
        delete obj.createTime
        let params = {
          [this.comName]: obj
        }
        editStrategy(
          this.dialogData.params.id,
          params,
          (response) => {
            this.$message.success('操作成功！')
            this.$emit('refresh')
            this.cancelLabel()
            this.loading = false
          },
          (response) => {
            this.loading = false
            this.$message({
              message: '编辑失败，' + response.message,
              type: 'warning'
            })
          }
        )
      })
    }
  }
}
</script>
<style lang="less">
#dialogIntegralActionEdit {
  .margin0 {
    margin-bottom: 0 !important;
  }
  .form-title {
    font-weight: bold;
    font-size: 16px;
    padding-top: 5px;
  }
  .small {
    .el-input-number--mini {
      width: 70px;
      margin-right: 5px;
      .el-input__inner {
        padding-left: 5px;
        padding-right: 5px !important;
      }
    }
  }
  .date-line {
    display: inline-block;
    margin-left: 10px;
    .el-range-separator,
    .el-range__icon {
      line-height: 26px;
    }
  }
  .taskValidity {
    height: 40px;
  }
  .tips-box {
    color: #f00;
  }
}
</style>
